<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\User;
use think\Validate;

/**
 * 认证接口
 * @ApiWeigh (100)
 */
class Auth extends Api
{
    protected $noNeedLogin = ['login', 'mobileLogin', 'wxLogin', 'wxAuth'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 手机号验证码登录
     * 
     * @ApiTitle    (手机号验证码登录)
     * @ApiSummary  (通过手机号和验证码进行登录认证)
     * @ApiMethod   (POST)
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams   (name="code", type="string", required=true, description="验证码")
     * @ApiReturn   ({
        "code": 1,
        "msg": "登录成功",
        "data": {
          "token": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
          "user": {
            "id": 1,
            "mobile": "13800138000",
            "nickname": "用户昵称",
            "avatar": "头像地址",
            "createtime": "2024-01-01 00:00:00",
            "im_userid": "im用户id",
            "im_sign": "im用户签名"
          }
        }
      })
     */
    public function mobileLogin()
    {
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        
        $validate = new Validate([
            'mobile' => 'require|regex:/^1[3-9]\d{9}$/',
            'code' => 'require|number|length:6'
        ]);

        if (!$validate->check(['mobile' => $mobile, 'code' => $code])) {
            $this->error($validate->getError());
        }

        $ret = \app\common\library\Sms::check($mobile, $code, 'mobilelogin');
        if (!$ret) {
            $this->error('验证码错误');
        }

        $user = User::where('mobile', $mobile)->find();
        $isFirstLogin = false;
        if (!$user) {
            $isFirstLogin = true;
            $user = new User;
            $user->mobile = $mobile;
            $user->is_teacher = 0;
            $user->username = $mobile;
            $user->nickname = '手机用户_' . substr($mobile, -4);
            $user->save();
        }
        // 使用框架自带的登录方法
        $this->auth->direct($user->id);
        $im_user_id = "guoxue_user_{$user->id}";
        $tenApi = new TLSSigAPIv2();
        $im_user_sig = $tenApi->genUserSig($im_user_id);
        
        // 更新用户的 IM 信息
        $user->im_userid = $im_user_id;
        $user->save();
        
        $this->success('登录成功', [
            'token' => $this->auth->getToken(), 
            'user' => $user,
            'im_userid' => $im_user_id,
            'im_sign' => $im_user_sig,
            'is_first_login' => $isFirstLogin
        ]);
    }

    /**
     * 微信授权
     * 
     * @ApiTitle    (微信授权)
     * @ApiSummary  (通过微信授权码进行登录认证)
     * @ApiMethod   (POST)
     * @ApiParams   (name="code", type="string", required=true, description="微信授权码")
     * @ApiReturn   ({
        "code": 1,
        "msg": "登录成功",
        "data": {
          "token": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
          "user": {
            "id": 1,
            "openid": "微信openid",
            "nickname": "用户昵称",
            "avatar": "头像地址",
            "createtime": "2024-01-01 00:00:00",
            "im_userid": "im用户id",
            "im_sign": "im用户签名"
          }
        }
      })
     */
    public function wxAuth()
    {
        $code = $this->request->post('code');
        if (!$code) {
            $this->error('参数错误');
        }

        $wx = new \app\common\library\Wechat;
        $userInfo = $wx->getUserInfo($code);
        
        if (!$userInfo) {
            $this->error('微信授权失败');
        }

        $user = User::where('openid', $userInfo['openid'])->find();
        $isFirstLogin = false;
        if (!$user) {
            $this->success('授权成功', [
                'openid' => $userInfo['openid'], 
                'nickname' => $userInfo['nickname'],
                'avatar' => $userInfo['headimgurl'],
            ],2);
        }

        // 使用框架自带的登录方法
        $this->auth->direct($user->id);
        $im_user_id = "guoxue_user_{$user->id}";
        $tenApi = new TLSSigAPIv2();
        $im_user_sig = $tenApi->genUserSig($im_user_id);
        
        // 更新用户的 IM 信息
        $user->im_userid = $im_user_id;
        $user->save();
        
        $this->success('登录成功', [
            'token' => $this->auth->getToken(), 
            'user' => $user,
            'im_userid' => $im_user_id,
            'im_sign' => $im_user_sig,
            'is_first_login' => $isFirstLogin
        ]);
    }
    /**
     * 微信+手机号登录
     * 
     * @ApiTitle    (微信+手机号登录)
     * @ApiSummary  (通过微信+手机号登录)
     * @ApiMethod   (POST)
     * @ApiParams   (name="openid", type="string", required=true, description="微信openid")
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams   (name="nickname", type="string", required=true, description="微信昵称")
     * @ApiParams   (name="avatar", type="string", required=true, description="微信头像")
     * @ApiParams   (name="code", type="string", required=true, description="验证码")
     * @ApiReturn   ({
        "code": 1,
        "msg": "登录成功",
        "data": {
          "token": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
          "user": {
            "id": 1,
            "openid": "微信openid",
            "nickname": "用户昵称",
            "avatar": "头像地址",
            "createtime": "2024-01-01 00:00:00",
            "im_userid": "im用户id",
            "im_sign": "im用户签名"
          }
        }
      })
     */
    public function wxLogin()
    {
        $code = $this->request->post('code');
        if (!$code) {
            $this->error('参数错误');
        }
        $openid = $this->request->post('openid');
        $mobile = $this->request->post('mobile');
        $nickname = $this->request->post('nickname');
        $code = $this->request->post('code');
        $avatar = $this->request->post('avatar');
        if (!$openid || !$mobile || !$nickname || !$avatar || !$code) {
            $this->error('参数错误');
        }
        $ret = \app\common\library\Sms::check($mobile, $code, 'mobilelogin');
        if (!$ret) {
            $this->error('验证码错误');
        }
        $user = User::where('mobile', $mobile)->find();
        if ($user) {
            if($user['openid'] && $user['openid'] != $openid){
                $this->error('手机号已绑定其他账号');
            }
            $this->auth->direct($user->id);
            $im_user_id = "guoxue_user_{$user->id}";
            $tenApi = new TLSSigAPIv2();
            $im_user_sig = $tenApi->genUserSig($im_user_id);
            
            // 更新用户的 IM 信息
            $user->im_userid = $im_user_id;
            $user->openid = $openid;
            $user->nickname = $nickname;
            $user->avatar = $avatar;
            $user->save();
            $this->success('登录成功', [
                'token' => $this->auth->getToken(), 
                'user' => $user,
                'im_userid' => $im_user_id,
                'im_sign' => $im_user_sig,
                'is_first_login' => false
            ]);
        }else{
            $user = User::where('openid', $openid)->find();
            $isFirstLogin = false;
            if(!$user){
                $isFirstLogin = true;
                $user = new User;
                $user->openid = $openid;
                $user->mobile = $mobile;
                $user->is_teacher = 0;
                $user->nickname = $nickname;
                $user->avatar = $avatar;
                $user->save();
            }
            // 使用框架自带的登录方法
            $this->auth->direct($user->id);
            $im_user_id = "guoxue_user_{$user->id}";
            $tenApi = new TLSSigAPIv2();
            $im_user_sig = $tenApi->genUserSig($im_user_id);
            
            // 更新用户的 IM 信息
            $user->im_userid = $im_user_id;
            $user->save();
            $this->success('登录成功', [
                'token' => $this->auth->getToken(),
                'user' => $user,
                'im_userid' => $im_user_id,
                'im_sign' => $im_user_sig,
                'is_first_login' => $isFirstLogin
            ]);
        }
    }
    /**
     * 初始化IM用户信息
     * @ApiTitle    (初始化IM用户信息，前端IM初始化完成后调用)
     * @ApiSummary  (初始化IM用户信息，前端IM初始化完成后调用)
     * @ApiMethod   (POST)
     * @ApiReturnParams   (name="code", type="int", description="状态码 1=成功 0=失败")
     * @ApiReturnParams   (name="msg", type="str", description="状态说明")
     * @ApiReturnParams   (name="time", type="str", description="接口响应时间戳")
     * @ApiReturnParams   (name="data", type="arr", description="返回数据")
     * @ApiReturnParams   (name="data.user_id", type="int", description="用户id")
     * @ApiReturnParams   (name="data.im_user_id", type="str", description="IM userId")
     * @ApiReturnParams   (name="data.im_user_sig", type="str", description="IM userSig")
     */
    public function setImUserInfo(){
        $common = new Common();
        $res = $common->setImUserInfo("guoxue_user_{$this->auth->id}",$this->auth->nickname,cdnurl($this->auth->avatar));
        $this->success('初始化成功',json_decode($res,true));
    }
}